﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinExamReader
{
    public partial class frmMain : Form
    {
        DataTable dtData = new DataTable();
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnImportNames_Click(object sender, EventArgs e)
        {
            try
            {
                if (ofdNames.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    DataTable dt = ExcelHelper.GetDataTableFromExcel(ofdNames.FileName, false);
                    CreateNames(dt);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        /// <summary>
        /// 根据姓名数据创建列
        /// </summary>
        /// <param name="dt">exlce读取到的名单</param>
        private void CreateNames(DataTable dt)
        {
            this.dtData.Columns.Add("题号");
            this.dtData.Columns.Add("答案");
            foreach (DataRow dr in dt.Rows)
            {
                this.dtData.Columns.Add(dr[0].ToString());
            }
            dgvData.DataSource = this.dtData;
            for (int i = 0; i < this.dgvData.Columns.Count; i++)
            {
                this.dgvData.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                //this.dtData.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            }
        }

        private void btnImportAnswers_Click(object sender, EventArgs e)
        {
            try
            {
                if (ofdAnswer.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    DataTable dt;
                    if (ofdAnswer.FileName.Contains(".xls"))
                    {
                        dt = ExcelHelper.GetDataTableFromExcel(ofdAnswer.FileName, false);

                    }
                    else
                    {
                        dt = WordHelper.ReadAnswer(ofdAnswer.FileName);
                    }
                    ReadAnswer(dt);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ReadAnswer(DataTable dt)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dtData.NewRow();
                dr[0] = dt.Rows[i][0].ToString();
                dr[1] = dt.Rows[i][1].ToString().ToUpper();

                dtData.Rows.Add(dr);
            }
            DataRow dr1 = dtData.NewRow();
            dr1[0] = "得分";
            dr1[1] = "";

            for (int i = 2; i < dtData.Columns.Count; i++)
            {
                dr1[i] = 0;
            }
            dtData.Rows.Add(dr1);
        }

        private void btnImportStudent_Click(object sender, EventArgs e)
        {
            try
            {
                if (fbdStudents.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {

                    DirectoryInfo di = new DirectoryInfo(fbdStudents.SelectedPath);
                    FileInfo[] arr = di.GetFiles();

                    foreach (FileInfo fi in arr)
                    {
                        if (fi.Name.Contains("答案"))
                        {
                            continue;
                        }
                        try
                        {
                            //从文件名截取学生姓名
                            string stuName = fi.Name.Substring(fi.Name.IndexOf('_') + 1, fi.Name.IndexOf('.') - fi.Name.IndexOf('_') - 1);
                            string fileName = fi.FullName;
                            //读取学生的答案
                            DataTable dt = ExcelHelper.GetDataTableFromExcel(fileName, true);
                            int score = 0;
                            foreach (DataRow dr in dt.Rows)//逐行读取
                            {
                                string id = dr[0].ToString().Trim();//获取该行的题号
                                string answer = dr[1].ToString().ToUpper().Trim();//获取该行的答案
                                if (WriteAnswer(id, answer, stuName))//把答案写入成绩单，答对返回true
                                {
                                    score += int.Parse(nudScore.Value.ToString());//答对加分
                                }
                            }
                            if (dt.Columns[0].ColumnName.Trim().Equals("1"))
                            {
                                string id = "1";
                                string answer = dt.Columns[1].ColumnName.ToUpper().Trim();
                                if (WriteAnswer(id, answer, stuName))
                                {
                                    score += int.Parse(nudScore.Value.ToString());
                                }
                            }
                            dtData.Rows[dtData.Rows.Count - 1][stuName] = score;//写入学生的最终成绩
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(fi.Name+"出错："+ex.Message);
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        /// <summary>
        /// 向成绩单写入答案
        /// </summary>
        /// <param name="id">题号</param>
        /// <param name="answer">选择的答案</param>
        /// <param name="stuName">选择人</param>
        /// <returns></returns>
        private bool WriteAnswer(string id, string answer, string stuName)
        {
            for (int i = 0; i < dtData.Rows.Count; i++)
            {
                if (dtData.Rows[i][0].ToString().Equals(id))
                {
                    dtData.Rows[i][stuName] = answer;
                    if (answer.Equals(dtData.Rows[i][1].ToString()))
                    {
                        return true;
                    }
                    return false;
                }
            }
            return false;
        }

        private void dgvData_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {

        }

        private void dgvData_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {

        }

        private void btnImportSingle_Click(object sender, EventArgs e)
        {
            try
            {
                if (ofdNames.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        string fileName = ofdNames.FileName.Substring(ofdNames.FileName.LastIndexOf("\\") + 1);
                        string stuName = fileName.Substring(fileName.IndexOf('_') + 1, fileName.IndexOf('.') - fileName.IndexOf('_') - 1);

                        DataTable dt = ExcelHelper.GetDataTableFromExcel(ofdNames.FileName, true);

                        int score = 0;
                        foreach (DataRow dr in dt.Rows)
                        {
                            string id = dr[0].ToString().Trim();
                            string answer = dr[1].ToString().ToUpper().Trim();
                            if (WriteAnswer(id, answer, stuName))
                            {
                                score += int.Parse(nudScore.Value.ToString());
                            }
                        }
                        if (dt.Columns[0].ColumnName.Trim().Equals("1"))
                        {
                            string id = "1";
                            string answer = dt.Columns[1].ColumnName.ToUpper().Trim();
                            if (WriteAnswer(id, answer, stuName))
                            {
                                score += int.Parse(nudScore.Value.ToString());
                            }
                        }
                        dtData.Rows[dtData.Rows.Count - 1][stuName] = score;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnSummary_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("姓名");
            dt.Columns.Add("成绩", typeof(int));

            for (int i = 2; i < this.dtData.Columns.Count; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = this.dtData.Columns[i].ColumnName;
                dr[1] = this.dtData.Rows[this.dtData.Rows.Count - 1][this.dtData.Columns[i].ColumnName].ToString();
                dt.Rows.Add(dr);
            }

            frmSummary frm = new frmSummary();
            frm.dt = dt;
            frm.Show();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                sfd.FileName = DateTime.Now.ToString("yyyy-MM-dd") + "测试结果.xls";
                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    ExcelHelper.SaveTable(dgvData, sfd.FileName);
                    MessageBox.Show("保存成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要清空人名、答案以及所有结果吗？", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
            {
                dtData = new DataTable();
                dgvData.DataSource = null;
                MessageBox.Show("清除成功，请重新从导入人名开始操作。", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void dgvData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            Console.WriteLine("111");
            if (e.RowIndex < 0)
                return;
            if (e.ColumnIndex > 1 && dtData.Rows.Count > 0 && e.RowIndex < dtData.Rows.Count - 1)
            {
                string answer = dgvData.Rows[e.RowIndex].Cells[1].Value.ToString();
                if (!e.Value.ToString().Equals(answer))
                {
                    dgvData.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Red;
                }
                else
                {
                    dgvData.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
                }
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            Version ApplicationVersion = new Version(Application.ProductVersion);
            //追加版本号
            this.Text += string.Format("v{0}.{1}", ApplicationVersion.Major, ApplicationVersion.Minor);
        }

        private void dgvData_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
        {
            if (e.Column.Name.Length > 2)
            {
                e.Column.Width = 50;
            }
            else
            {
                e.Column.Width = 40;
            }
        }
    }

}
